//配置路由的地方
import Vue from "vue";
import VueRouter from "vue-router";
import routes from './routes';
//引入仓库
import store from '@/store'

//使用路由插件
Vue.use(VueRouter)


//重写push|replace方法,当重复传一个参数时，一劳永逸
let originPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        //当传了成功与失败的回调时
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}
let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        //当传了成功与失败的回调时
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}

//配置路由
let router = new VueRouter({
    routes,
    //让路由跳转后，自动滚轮在最上方
    scrollBehavior() {
        return { y: 0 }
    }
})

//全局前置路由守卫
router.beforeEach(async (to, from, next) => {

    let token = store.state.user.token;
    //用户信息
    let name = store.state.user.userInfo.name
    //用户已经登录(有token)
    if (token) {
        if (to.path == '/login' || to.path == '/register') {
            //用户已经登录，但还是去login（不能去，跳转到主页）
            next("/home")
        } else {
            //用户登录，且去的不是登陆界面
            //如果已经有了用户名
            if (name) {
                next();

            } else {
                //没有用户信息，再派发actions让仓库存储用户信息再跳转
                try {
                    await store.dispatch('getUserInfo')
                    next()
                } catch (error) {
                    //若失败，再是token失效了获取不到用户信息，再要重新登录
                    //要清除token
                    await store.dispatch('userLogout')
                    //跳转到登录界面
                    next('/login')
                }
            }
        }
    } else {
        //用户未登录
        //要去的路由
        let toPath = to.path
        //去登录，要去订单，支付或者订单详情页面
        if (toPath.indexOf('/trade') != -1 || toPath.indexOf('/pay') != -1 || toPath.indexOf('/center') != -1) {
            //把未登录时要去的路由存一下,存在query参数中
            //方便登录之后直接跳转到本来要去的路由
            next("/login?redirect=" + toPath)
        } else {
            //未登录，去的不是以后路由,放行
            next()
        }
    }
})


export default router
